# -*- coding: utf-8 -*- 
# @Time : 2021/10/23 22:07 
# @Author : Dong 
# @File : profile.py
from flask_restful import Resource

from ihome import constants, db
from ihome.utils.commons import login_status, data_base_error
from flask import g, request, jsonify, current_app, session

from ihome.utils.image_storage import storage
from ihome.utils.response_code import RET, error_map


class Set_user_avatar(Resource):

    @login_status
    @data_base_error
    def post(self):

        image_file = request.files.get('avatar')

        if image_file is None:
            return jsonify(constants.return_template_json(RET.PARAMERR, error_map.get(RET.PARAMERR)))

        image_data = image_file.read()

        # 上传
        try:
            file_name = storage(image_data)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(constants.return_template_json(RET.THIRDERR, error_map.get(RET.THIRDERR)))

        g.user.avatar_url = file_name
        db.session.commit()

        return jsonify(constants.return_template_json(RET.OK, error_map.get(RET.OK),{'avatar_url':file_name}))

    @login_status
    def get(self):
        return jsonify(constants.return_template_json(RET.OK, error_map.get(RET.OK), {'user_name': g.user.name}))
